<?php
Namespace Cyfy;

/**
 * Install file
 *
 * @author Dandelion <dandelion8888@gmail.com>
 * @package cyfy
 *
 */

if(file_exists("cfg/Cyfy.php") == false || file_exists(".htaccess") == false){
 
    
     $inputs = array(
        'dbHost' =>  'DB host',
        'dbUsername' => 'DB username',
        'dbPassword' => 'DB password',
        'dbDatabase' => 'DB database',
        'dbPrefix' => 'DB table prefix',
    );

    if($_GET['datasend'])
    {
        $uri = $_SERVER["REQUEST_URI"];
        $uri = substr($uri, 0, strrpos($uri, "/"));
 
    
        $files = scandir("install/");
        array_shift($files);
        array_shift($files);
        $trans = $_GET;
        $trans["pathPrefix"] = $uri;
        foreach($files as $file)
        {
            $data = file_get_contents("install/" . $file);
            foreach($trans as $i => $title)
            {
                $data = strtr($data, array("###{$i}###" => $trans[$i]));
            }    
            file_put_contents("tmp/" . $file, $data);
        }  
        print "<h2>Files created</h2>";
        print "<p>Move file tmp/Cyfy.php to /cfg</p>";
        print "<p>Move tmp/.htaccess to /</p>";
        print "<h1>Then HIT F5!</h1>";
        die();
    }
        ?>
    <h1>Cyfy install script</h1>
<h2>Folders:</h2>
<ul>
    <li>log</li>
    <li>tmp</li>
    <li>files</li>
</ul>
<h3>Must be 0777.</h3>
<br /><br /><br />
<h2>Config:</h2>
<form method = "GET">
<?php
$output = '';

foreach($inputs as $i => $title){
    $output .= "<p>" . $title . ": <input type=\"text\" name=\"{$i}\"></p>";
}
print $output;
?>

<input type="hidden" value="true" name="datasend" />
<input type="submit" value="Create config files" />
</form>
 <?php

    die("cyfy is not installed. Fill in and send the form above");
}
 
 
 
 
 
 /* FILES CREATED, starting cyfy */
 
 // Including the files
include_once('functions.php'); //autoloading
include_once('cyfy.php');
include_once('cfg/cyfy.php');
include_once('dibi-1.2/dibi.minified/dibi.min.php');

// error handler
ini_set("display_errors", "On");
ini_set("error_reporting", E_ALL & ~E_NOTICE);

// log start
\Cyfy\Log :: start(true);

// DIBI CONNECT
\dibi::connect(array(
    'driver'   => \Cyfy\Cyfy ::  $dbDriver,
    'host'     => \Cyfy\Cyfy ::  $dbHost,
    'username' => \Cyfy\Cyfy ::  $dbUsername,
    'password' => \Cyfy\Cyfy ::  $dbPassword,
    'database' => \Cyfy\Cyfy ::  $dbDatabase,
    'charset'  => 'utf8',
));

// DIBI TABLE PREFIX
\dibi::addSubst('cyfy', \Cyfy\Cyfy ::  $dbPrefix);

// Starting session
session_start();

// Crops the URL, if contains / at the end
\Cyfy\Cyfy ::  $query = $_GET["q"];
if(preg_match("/\/$/",\Cyfy\Cyfy ::  $query))
{
	\Cyfy\Cyfy ::  $query = substr(\Cyfy\Cyfy ::  $query, 0, -1);
}

// CREATES TABLES
\Cyfy\Modules\Modules\Module :: callCreateTables();

// Initializing basic settings
\Cyfy\Modules :: prepare();
\Cyfy\Modules :: loadStarters();

if($_GET['userUsername']){
    $_SESSION['userUsername'] = $_GET['userUsername'];
}

if($_GET['userPassword']){
    $_SESSION['userPassword'] = $_GET['userPassword'];
}

/* INSTALL PART */
print "<h1>Cyfy install script</h1>";
print "
<h2>Your user account</h2>
<form method='get'>
<p>Username: <input type='text' name='userUsername' value='{$_SESSION['userUsername']}' /></p>
<p>Password: <input type='text' name='userPassword' value='{$_SESSION['userPassword']}' /></p>
<input type=\"submit\" value=\"Set\" />
</form>
";

if(!$_SESSION['userPassword'] || !$_SESSION['userUsername'])
{
    die('Enter your account username and password for your account.');
}


// module toInstall
$toInstall = array();
$installed = array();
// get all
foreach(\Cyfy\Modules\Modules\Module :: loadModules() as $module)
{
    $info = \Cyfy\Modules :: getInfo($module);
    if(!$info) continue;
    
    if(\Cyfy\Modules :: isEnabled($module))
    {
        $installed[] = $module;
    }
    else{
        $toInstall[] = $info;
    }
}

if(count($toInstall))
{
    print "<h1>Hit F5 until all modules are installed!</h1>";
}else{
    
    print "<h2>Remove install.php and /install directory!</h2>";
    print "<h1>Installation successful, now continue to <a href=\"user/login\">login</a> and use values you entered.</h1>";
    unset($_SESSION["templateMessages"]);
}

// which to install?
foreach($toInstall as $info)
{
    // met dependencies?
    $thisInstall = true;
    if(count($info['dependencies']))
    {
        foreach($info['dependencies'] as $d)
        {
            if(!in_array($d, $installed)){
                $thisInstall = false;
                print "<p>Not installed: " . $info['classname'] . " - because of {$d}.</p>";
                break;
            }
        }
    }
    if($thisInstall == false) continue;
    
    // proceed to install
    $installing++;
    \Cyfy\Modules\Modules\Module :: changeState(array(
        'module-classname' => $info['classname'],
        'module-do' => 'install-run'));
    print "<p>Installed: " . $info['name'] . "</p>";
}



include('_end.php');
